<?php

/**
 * profile actions.
 *
 * @package    sf_sandbox
 * @subpackage profile
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class profileActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */

    
	 public function executeDel_avatar(sfWebRequest $request)
  {
  	    $pf = $this->getUser()->getProfile();
  	    $dir = sfConfig::get('sf_upload_dir').'/users/avatar/'.$pf->getPhoto();
  	    $dir1 = sfConfig::get('sf_upload_dir').'/users/avatar/_thumbnail/'.$pf->getPhoto();
  	    $dir2 = sfConfig::get('sf_upload_dir').'/users/avatar/thumbnail/'.$pf->getPhoto();
  	    @unlink($dir);
  	    @unlink($dir1);
  	    @unlink($dir2);
  	    $pf->setPhoto('');
  	    $pf->save();
  		$this->redirect('profile/myprofile');
  }
	
  public function executeEdit(sfWebRequest $request)
  {
  	$strform = sfConfig::get('app_name').'ProfileForm';
  	$this->setDecorator();
  	   ////Проверка на регистрацию
    	if(!$this->getUser()->isAuthenticated())
		  	{
		  	 $this->getUser ()->setFlash ( 'error', 'Только для зарегистрированных пользователей' );
		  	$this->redirect('@registration');
		  	}
  	   ///
  	
  	if($this->getUser()->isAuthenticated())
  	{
  		if($this->getUser()->isSuperAdmin())
  		{
  			if($request->getParameter('id'))
  			{
  			$pf = sfGuardUserPeer::retrieveByPK($request->getParameter('id'));	
  			}
  			else 
  			{
  			 $pf = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
  			}
  		}
  		else {
  		$pf = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
  		}
  		
  		$this->form = new $strform($pf);
  	}
  	else 
  	{
  		$this->redirect('@homepage');
  	}
  	
   if ($request->isMethod('post'))
    {
    	//$pf = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
        $this->form = new $strform($pf);
    	$this->form->bind($request->getParameter('user'), $request->getFiles('user'));
    if ($this->form->isValid())
      {
      	    $this->getUser ()->setFlash ( 'notice', 'Данные сохранены.' );
         	$this->form->save();
         	$pf = $this->form->getObject();
          ////Сохраняем мултики
            if($request->getParameter('user[cmy_read][]'))
            {
            	$arr = array();
            	$arr = $request->getParameter('user[cmy_read]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyRead($str);
            }
            if($request->getParameter('user[cmy_musik][]'))
            {
            	$arr = array();
            	$arr = $request->getParameter('user[cmy_musik]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyMusik($str);

            }        	
            if($request->getParameter('user[cmy_rest][]'))
            {
            	$arr = array();
            	$arr = $request->getParameter('user[cmy_rest]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyRest($str);
            }   
            if($request->getParameter('user[cmy_harakter][]'))
            {
            	$arr = $request->getParameter('user[cmy_harakter]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyHarakter($str);
            }  
            if($request->getParameter('user[cmy_food][]'))
            {
            	$arr = $request->getParameter('user[cmy_food]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyFood($str);
            }
            if($request->getParameter('user[cmy_sport][]'))
            {
            	$arr = $request->getParameter('user[cmy_sport]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMySport($str);
            }            
            $pf->save();
         	///
         	
         	$this->redirect('@show_profile?id='.$pf->getId());
      }
    }
  		 ///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $pf);
		////
  }
  
  public function executeWelcome(sfWebRequest $request)
  {
  	$this->setDecorator();
    if(!$this->getUser()->isAuthenticated())$this->redirect('@homepage');
    		 //Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////
  }
  
  public function executeMyprofile(sfWebRequest $request)
  {
  	
  	/*
  	 * отправляем письма всем мужчинам
  	 */
  	if($request->getParameter('int_letter')) {
  		$user = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
  		$c = new Criteria ( );
		$c->add ( sfGuardUserPeer::GENDER, 'm' );
		$cnt = sfGuardUserPeer::doSelect( $c );
		foreach ($cnt as $cnt) {
				//echo "-".$cnt->getId()."<br>";
				$m=new Mailbox();
				$m->setFromId($user->getId());
				$m->setToId($cnt->getId());
				$m->setBody($user->getIntroductionLetter());
				$m->setPub(1);
				$m->save();

				//// Шлем уведомление	
				$not = MailnoticePeer::retrieveByPK ( 3 );
				$title = $not->getTitle ();
				$body = $not->parse_body ( array ('%from%' => $user->getUsername(), '%link%' => "<a href='" . sfConfig::get ( 'app_site_url' ) . url_for ( '@mailbox_input' ) . "'>" . __ ( 'ссылку' ) . "</a>" ) );
				myTools::sendMail ( $cnt->getEmail(), $title, $body );				
		}
  	}

       
      if(!$this->getUser()->isAuthenticated())$this->redirect('@home');

  	
  	 $this->forward404Unless($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' )); 
     $this->user = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
     $this->getRequest()->setAttribute('v', $this->user);
    ///Передаем массивы стран и языков    
    $this->arrc = sfCultureInfo::getInstance($this->getUser()->getCulture())->getCountries();
    $this->arrl = sfCultureInfo::getInstance($this->getUser()->getCulture())->getLanguages();    
    ////
    
     
  }
  
  public function executeShow(sfWebRequest $request)
  {
  	
  	$this->setDecorator();
  	if (isset($_SESSION['count_show_profile'])) {
  		$_SESSION['count_show_profile'] = $_SESSION['count_show_profile']+1;
  	} else {
  		$_SESSION['count_show_profile'] = 1;
  	}
  	 
    if(!$this->getUser()->isAuthenticated() and $_SESSION['count_show_profile']>sfConfig::get('app_count_show_profile')){
    	$this->getUser ()->setFlash ( 'message', 'Для просмотра профайла вам необходимо зарегистрироваться' );
    	$this->redirect('@registration');
    }
    
    
    $this->user = sfGuardUserPeer::retrieveByPK($request->getParameter('id'));

    ///Редирект на свой профайл если это хозяин
     if($this->user->getId()==$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' )) $this->redirect('@my_profile');
    //
    $this->getRequest()->setAttribute('v', $this->user);

    $this->v = sfGuardUserPeer::retrieveByPK($request->getParameter('id'));
    $this->forward404Unless($this->user); 
    
    ///Записываем интерес
    if($this->getUser()->isAuthenticated())
    {
    	$c = new Criteria();
    	$c->add(InterestPeer::USER_ID,$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
    	$c->add(InterestPeer::INTEREST_ID,$this->user->getId());
    	$cnt = InterestPeer::doCount($c);
    	if($cnt==0 and $this->user->getId()!=$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ))
    	{
		    $i = new Interest();
		    $i->setUserId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
		    $i->setInterestId($this->user->getId());
		    $i->save();
    	}
    }
    //
    
    ///Передаем массивы стран и языков    
    $this->arrc = sfCultureInfo::getInstance($this->getUser()->getCulture())->getCountries();
    $this->arrl = sfCultureInfo::getInstance($this->getUser()->getCulture())->getLanguages();    
     $this->getRequest()->setAttribute('arrc', $this->arrc);
     $this->getRequest()->setAttribute('arrl', $this->arrl);
    ////
   
    
    
  }
 
  public function executeAddprofile(sfWebRequest $request)
  {
  	$strform = sfConfig::get('app_name').'ProfileForm';
  	$this->setDecorator();
    $pf = new sfGuardUser();
  	$this->form = new $strform($pf);
  	
  }
  
  
   public function executeAdd_child(sfWebRequest $request)
  {
  	 $this->setDecorator();
  	$this->form = new ChildForm();
     if ($request->isMethod('post'))
    {
    	//$pf = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
    	$this->form->bind($request->getParameter('child'), $request->getFiles('child'));
    if ($this->form->isValid())
      {
      	    $this->getUser ()->setFlash ( 'notice', 'Данные сохранены.' );
         	$this->form->save();
         	$this->redirect('@edit_profile?id='.$this->form->getObject()->getsfGuardUser()->getId());
      }
    }
    ///Кидаем пользователя в layout
	     $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
	////
  }
  
  public function executeDel_child(sfWebRequest $request)
  {
  	 $u2l = ChildPeer::retrieveByPK($request->getParameter('id'));
  	 $u2l->delete();
  	 $this->redirect('@edit_profile?id='.$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
  }
  
  
  
   public function executeAdd_language(sfWebRequest $request)
  {
  	 $this->setDecorator();
  	$u2l = new User2lang();
  	$u2l->setUserId($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
  	$this->form = new User2langForm($u2l);
     if ($request->isMethod('post'))
    {
    	//$pf = sfGuardUserPeer::retrieveByPK($this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
    	$this->form->bind($request->getParameter('user2lang'));
    if ($this->form->isValid())
      {
      	    $this->getUser ()->setFlash ( 'notice', 'Данные сохранены.' );
         	$this->form->save();
         	$this->redirect('@edit_profile?id='.$this->form->getObject()->getsfGuardUser()->getId());
      }
    }
  		 ///Кидаем пользователя в layout
	    $this->getRequest()->setAttribute('v', $this->getUser()->getProfile());
		////    
  }
  
  public function executeDel_language(sfWebRequest $request)
  {
  	 $u2l = User2langPeer::retrieveByPK($request->getParameter('id'));
  	 $u2l->delete();
  	 $this->redirect('@edit_profile?id='.$this->getUser()->getAttribute( 'user_id', null, 'sfGuardSecurityUser' ));
  }
  
  
   public function executeDelete(sfWebRequest $request)
  {
    $id = $this->getUser()->getProfile()->getId();
  	$this->getUser()->signout();
  	$this->getUser ()->setFlash ( 'message', 'Ваш профайл удален' );
  	 $pf = sfGuardUserPeer::retrieveByPK($id);
  	 $pf->delete();
  	 
  	
  	 $this->redirect('@home');
  } 	
  
  public function executeDoneregistration(sfWebRequest $request)
  {
  	$this->setDecorator();  
    
  }
  
  
  
	public function setDecorator()
	{
		
		$module = $this->getRequest()->getParameter('module');
		$action = $this->getRequest()->getParameter('action');
		
		$path_layout = sfConfig::get('sf_app_template_dir').'/layouts/'.sfConfig::get('app_name').'/'.$module.'.php';
		$path_template = sfConfig::get('sf_app_module_dir').'/'.$module.'/templates/'.sfConfig::get('app_name').'/'.$action.'Success.php';
		if(file_exists($path_layout))
		{ $l = 'layouts/'.sfConfig::get('app_name').'/'.$module; }
		else
		{ $l = sfConfig::get('app_name').'_layout'; }
		if(file_exists($path_template))
		{ $t = sfConfig::get('app_name').'/'.$action; }
		else
		{ $t = $action; }
			
	/*
     * Установка layout
     */	
			$this->setLayout ( $l );
		
     /*
     *  Устанавливаем шаблон
     */
		
			$this->setTemplate ( $t );
	}




  public function executeStep1(sfWebRequest $request)
  {
      $this->form = new step1ProfileForm($this->getUser()->getProfile());
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter('user'), $request->getFiles('user'));
        if ($this->form->isValid())
          {
              $this->form->save();
              $this->redirect('profile/step2');
          }
        }
  }

  public function executeStep2(sfWebRequest $request)
  {
     $this->form = new step2ProfileForm($this->getUser()->getProfile());
        if ($request->isMethod('post'))
        {
            $this->form->bind($request->getParameter('user'), $request->getFiles('user'));
        if ($this->form->isValid())
          {
              $this->form->save();
	      $pf = $this->form->getObject();

              ////Добавляем признак заполненного профайла
              $pf->setFullProfile(true);
              ////

          ////Сохраняем мултики
            if($request->getParameter('user[cmy_read][]'))
            {
            	$arr = array();
            	$arr = $request->getParameter('user[cmy_read]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyRead($str);
            }
            if($request->getParameter('user[cmy_musik][]'))
            {
            	$arr = array();
            	$arr = $request->getParameter('user[cmy_musik]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyMusik($str);

            }
            if($request->getParameter('user[cmy_rest][]'))
            {
            	$arr = array();
            	$arr = $request->getParameter('user[cmy_rest]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyRest($str);
            }
            if($request->getParameter('user[cmy_harakter][]'))
            {
            	$arr = $request->getParameter('user[cmy_harakter]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyHarakter($str);
            }
            if($request->getParameter('user[cmy_food][]'))
            {
            	$arr = $request->getParameter('user[cmy_food]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMyFood($str);
            }
            if($request->getParameter('user[cmy_sport][]'))
            {
            	$arr = $request->getParameter('user[cmy_sport]');
            	$str = myTools::db_array_field($arr);
            	$pf->setMySport($str);
            }
            $pf->save();

              //$this->redirect('profile/mypage');
          }
        }
  }


    public function executeMypage(sfWebRequest $request)
  {
      $this->setLayout('layouts/alika/mypage');
  }

  
}
